package com.tianji.promotion.task;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.tianji.promotion.config.MessageConfiguration;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Set;
import java.util.UUID;

@Component
@Slf4j
@RequiredArgsConstructor
public class ListenExpireCouponToUser {

    private final MessageConfiguration messageConfiguration;
    /**
     * 该业务只是简洁版，只是写死发送验证码服务；真正的业务应该先查询优惠卷表，
     * 得到过期时间小于等于7天的用户优惠卷信息集合，
     * 然后根据userId远程调用用户信息得到用户手机号，在发送信息
     * */
    @XxlJob("listenExpireCouponSendMessageToUser")//每天早上八点半执行一次
    public void listenExpireCouponSendMessageToUser(){
        log.info("监听优惠券过期");
        //生产环境请求地址：app.cloopen.com
        String serverIp = messageConfiguration.getServerIp();
        //请求端口
        String serverPort = messageConfiguration.getServerPort();
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = messageConfiguration.getAccountSId();
        String accountToken = messageConfiguration.getAccountToken();
        //请使用管理控制台中已创建应用的APPID
        String appId = messageConfiguration.getAppId();
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String phone = "19137182708";
        String templateId= "1";
        String code= UUID.randomUUID().toString();
        String[] datas = {code,"1"};
        String subAppend="1234";  //可选 扩展码，四位数字 0~9999
        String reqId="fadfafas";  //可选 第三方自定义消息id，最大支持32位英文数字，同账号下同一自然天内不允许重复
        //HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
        HashMap<String, Object> result = sdk.sendTemplateSMS(phone,templateId,datas,subAppend,reqId);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for(String key:keySet){
                Object object = data.get(key);
                System.out.println(key +" = "+object);
            }
            log.info("发送成功");
        }else{
            //异常返回输出错误码和错误信息
            System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
        }
    }
}
